//
//  THPostViewController.swift
//  LaiLang
//
//  Created by David on 2017/2/6.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

@objc protocol THPostDelegate {
    @objc optional func postViewController(_ postViewController :THPostViewController, didFinishPost data: Data)
}

class THPostViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, LLItemSliderDataSource, LLMajorPickerDelegate, UITextViewDelegate {
    
    var tableView:UITableView!
    
    //sectio 0
    
    //row 0
    var toNameInput: UITextField!
    var toMajorBtn: LLDropDownButton!
    var toMajorPicker: LLMajorPicker!
    
    //row 1
    var contentInput: LLTextView!
    
    //section 1
    
    //row 0
    var backgroundSelector: LLItemSlider!
    var selectedBGId: Int = 0
    
    //row 1
    var fromNameInput: UITextField!
    var fromMajorBtn: LLDropDownButton!
    var fromMajorPicker: LLMajorPicker!
    
    //row 2
    var anonymousSwitch: UISwitch!
    
    //section 2
    //row 0
    var submitBtn: UIButton!
    
    var loadingView: LLFullScreenLoading!
    var delegate: THPostDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let navbar = LLAdaptHideNavBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64), title: "发布物品", navigator: navigationController)
        navbar.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(THPostViewController.submitPost))
        
        // Do any additional setup after loading the view.
        
        tableView = UITableView(frame: CGRect(x: 0, y: 44, width: view.bounds.width, height: view.bounds.height - 44), style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.keyboardDismissMode = .onDrag
        view.addSubview(tableView)
        
        loadingView = LLFullScreenLoading(frame: view.frame)
        loadingView.alpha = 0
        view.addSubview(loadingView)
        
        view.addSubview(navbar)
        
        toNameInput = UITextField(frame: CGRect(x: 16, y: 0, width: (view.bounds.width - 32)/2, height: 44))
        toNameInput.placeholder = "物品名称"
        toNameInput.addTarget(self, action: #selector(THPostViewController.textInputBegin), for: .editingDidBegin)
        
        toMajorBtn = LLDropDownButton(frame: CGRect(x: (view.bounds.width - 32)/2 + 16, y: 8, width: 0, height: 28))
        toMajorBtn.setTitle("TA的系别", for: .normal)
        toMajorBtn.center.x = view.bounds.width - 16 - toMajorBtn.frame.width/2
        toMajorBtn.foreground = UIColor.orange
        toMajorBtn.addTarget(self, action: #selector(THPostViewController.toggleToMajorPicker), for: .touchUpInside)
        
        contentInput = LLTextView(frame: CGRect(x: 16, y: 0, width: view.bounds.width - 32, height: 128))
        contentInput.placeholder = "物品描述"
        contentInput.font = UIFont.systemFont(ofSize: 14)
        contentInput.placeholderView.textColor = UIColor.lightGray
        contentInput.placeholderView.backgroundColor = UIColor.clear
        contentInput.textColor = UIColor.black
        contentInput.backgroundColor = UIColor.clear
        contentInput.maxLength = THMaxContentLength
        contentInput.weakDelegate = self
        
        backgroundSelector = LLItemSlider(frame: CGRect(x: 16, y: 4, width: view.bounds.width - 32, height: 44))
        backgroundSelector.showsHorizontalScrollIndicator = false
        backgroundSelector.dataSource = self
        backgroundSelector.selectedIndex = selectedBGId
        
        fromNameInput = UITextField(frame: CGRect(x: 16, y: 0, width: (view.bounds.width - 32)/2, height: 44))
        fromNameInput.placeholder = "物品名称"
        fromNameInput.addTarget(self, action: #selector(THPostViewController.textInputBegin), for: .editingDidBegin)
        
        fromMajorBtn = LLDropDownButton(frame: CGRect(x: (view.bounds.width - 32)/2 + 16, y: 8, width: 0, height: 28))
        fromMajorBtn.setTitle("你的系别", for: .normal)
        fromMajorBtn.center.x = view.bounds.width - 16 - fromMajorBtn.frame.width/2
        fromMajorBtn.foreground = UIColor.orange
        fromMajorBtn.addTarget(self, action: #selector(THPostViewController.toggleFromMajorPicker), for: .touchUpInside)
        
        anonymousSwitch = UISwitch(frame: CGRect(x: view.bounds.width - 64, y: 6, width: 0, height: 0))
        anonymousSwitch.addTarget(self, action: #selector(THPostViewController.toggleAnonymous), for: .valueChanged)
        
        toMajorPicker = LLMajorPicker(frame: CGRect(x: 0, y: view.bounds.height - 200, width: view.bounds.width, height: 200))
        toMajorPicker.tag = 38
        toMajorPicker.delegate = self
        view.addSubview(toMajorPicker)
        
        fromMajorPicker = LLMajorPicker(frame: CGRect(x: 0, y: view.bounds.height - 200, width: view.bounds.width, height: 200))
        fromMajorPicker.tag = 58
        fromMajorPicker.delegate = self
        view.addSubview(fromMajorPicker)
        
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1//2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 2
        case 1:
            return 2 //anonymousSwitch.isOn ? 2 : 3
        default:
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 && indexPath.row == 1{
            return 128
        }
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0{
            return 0.001
        }
        return 32
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        cell.selectionStyle = .none
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0:
                
                cell.addSubview(toNameInput)
//                cell.addSubview(toMajorBtn)
                break
            case 1:
//                cell.backgroundColor = LLColor.getColorFromTable(by: selectedBGId)
                cell.addSubview(contentInput)
                break
            default:
                break
            }
            break
        case 1:
            switch indexPath.row {
            case 0:
                cell.addSubview(backgroundSelector)
                break
            
//            case 1:
//                cell.textLabel?.text = "匿名发布"
//                cell.addSubview(anonymousSwitch)
//                break
            case 1://2:
                cell.addSubview(fromNameInput)
                cell.addSubview(fromMajorBtn)
                break
            case 2:
                break
            default:
                break
            }
            break
        default:
            break
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 1{
            return "选择背景"
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
        if section == 0{
            return "请注意留下您的联系方式"
        }
        return nil
    }
    
    func submitPost(){
        toNameInput.resignFirstResponder()
        contentInput.resignFirstResponder()
        fromNameInput.resignFirstResponder()
        fromMajorPicker.hide()
        toMajorPicker.hide()
        
        if checkInput(){
            THPostSubmit()
        }
    }
    
    //TODO: 弹窗提示
    func checkInput() -> Bool{
        if toNameInput.text == "" {
            print("物品名称为空")
            showAlert(msg: "请输入物品的名字")
            toNameInput.becomeFirstResponder()
            return false
        }
        
//        if toMajorPicker.selectedIndex == 0{
//            print("对方系别未选择")
//            showAlert(msg: "请选择TA的系别")
//            toMajorPicker.show()
//            return false
//        }
        
        if contentInput.text == "" {
            print("内容为空")
            showAlert(msg: "请输入物品描述")
            contentInput.becomeFirstResponder()
            return false
        }
        
//        if contentInput.text.characters.count < THMinCOntentLength{
//            print("内容要20字以上")
//            showAlert(msg: "内容要\(THMinCOntentLength)字以上")
//            contentInput.becomeFirstResponder()
//            return false
//        }
        
//        if fromNameInput.text == "" && !anonymousSwitch.isOn {
//            print("名字为空")
//            showAlert(msg: "请输入你的名字")
//            fromNameInput.becomeFirstResponder()
//            return false
//        }
//        
//        if fromMajorPicker.selectedIndex == 0 && !anonymousSwitch.isOn {
//            print("我方系别未选择")
//            showAlert(msg: "请选择你的系别")
//            fromMajorPicker.show()
//            return false
//        }
        
        return true
    }
    
    func showAlert(msg: String?){
        let alert = UIAlertController(title: msg, message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    func THPostSubmit(){
        print("post submit")
        let toName = toNameInput.text!
        let toMajor = JZMajorList[toMajorPicker.selectedIndex]
        let anonymous = anonymousSwitch.isOn ? 1 : 0
        
        var fromName = ""
        var fromMajor = ""
        if !anonymousSwitch.isOn{
            
            fromName = fromNameInput.text!
            fromMajor = JZMajorList[fromMajorPicker.selectedIndex]
        }
        let content = contentInput.text!
        let color = selectedBGId
        
        loadingView.alpha = 1
        let urlStr = "\(HJY_DOMAIN_NAME)/api/creategb?niming=\(anonymous)&taname=\(toName)&taxibie=\(toMajor)&xibie=\(fromMajor)&name=\(fromName)&color=\(color)&text=\(content)".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
        //NSCharacterSet(charactersIn: "`#%^{}\"[]|\\<>//") as CharacterSet
        
        print(urlStr ?? "url failed")
        if urlStr != nil{
            let url = URL(string: urlStr!)
            URLSession.shared.dataTask(with: url!) { (data:Data?, resp:URLResponse?, err:Error?) in
                DispatchQueue.main.async {
                    self.loadingView.alpha = 0
                }
                do{
                    if err != nil{
                        throw err!
                    }
                    print(String(data: data!, encoding: .utf8) ?? "data not utf8")
                    
                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                    let gbid = jsonData?.object(forKey: "gbid")
                    if gbid != nil{
                        DispatchQueue.main.async {
                            self.delegate?.postViewController?(self, didFinishPost: data!)
                            _ = self.navigationController?.popViewController(animated: true)
                        }
                    }
                    
                }catch let ex{
                    DispatchQueue.main.async {
                        self.showAlert(msg: "请求出错")
                    }
                    print(ex)
                }
                
                }.resume()
        }
        
    }
    
    func itemSlider(rowNumForItemSlider: LLItemSlider) -> Int {
        return LLColor.colorTable.count
    }
    
    func itemSlider(itemSlider: LLItemSlider, itemForRow at: Int) -> UIButton {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 36, height: 36))
        btn.layer.cornerRadius = 8
        btn.backgroundColor = LLColor.getColorFromTable(by: at)
        if at == selectedBGId{
            let tickImg = UIImageView(frame: CGRect(x: 0, y: 0, width: 16, height: 16))
            tickImg.center = CGPoint(x: 18, y: 18)
            tickImg.image = #imageLiteral(resourceName: "tick")
            btn.addSubview(tickImg)
        }
        return btn
    }
    
    func itemSlider(itemSizeForSlider: LLItemSlider) -> CGFloat {
        return 36
    }
    
    func itemSlider(spacingForItemSlider: LLItemSlider) -> CGFloat {
        return 8
    }
    
    func itemSlider(itemSlider: LLItemSlider, didClickItem at: Int) {
        print("select \(at)")
//        selectedBGId = at
//        tableView.reloadSections(NSIndexSet(index: 0) as IndexSet, with: .none)
    }
    
    func toggleAnonymous(){
        
        tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none)
    }
    
    func keepAboveKeyboard(textfield: UITextField){
        if textfield.tag == fromNameInput.tag {
            
        }
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        textInputBegin()
    }
    
    func textInputBegin(){
        toMajorPicker.hide()
        fromMajorPicker.hide()
    }
    
    func toggleToMajorPicker(){
        fromMajorPicker.hide()
        toNameInput.resignFirstResponder()
        contentInput.resignFirstResponder()
        fromNameInput.resignFirstResponder()
        toMajorPicker.toggleShowed()
    }
    func toggleFromMajorPicker(){
        toNameInput.resignFirstResponder()
        contentInput.resignFirstResponder()
        fromNameInput.resignFirstResponder()
        toMajorPicker.hide()
        fromMajorPicker.toggleShowed()
    }
    
    func majorPicker(_ picker: LLMajorPicker, selectedAt index: Int) {
        switch picker.tag {
        case toMajorPicker.tag:
            let text = picker.selectedIndex == 0 ? "TA的系别" : JZMajorList[picker.selectedIndex - 1]
            toMajorBtn.setTitle(text, for: .normal)
            toMajorBtn.center.x = view.bounds.width - 16 - toMajorBtn.frame.width/2
            break
        case fromMajorPicker.tag:
            let text = picker.selectedIndex == 0 ? "你的系别" : JZMajorList[picker.selectedIndex - 1]
            fromMajorBtn.setTitle(text, for: .normal)
            fromMajorBtn.center.x = view.bounds.width - 16 - fromMajorBtn.frame.width/2
            break
        default:
            break
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
